<script setup>
import _ from 'lodash';
import ParameterForm from './parameter-form.vue';
import { onMounted, reactive, ref, toRefs } from 'vue';
import { DFT_ICONS } from '@jzl/icons';
import { api } from '@jzl/api';
import { openCompInWin, useDataThemeChange } from '@jzl/comps';
import TenantProfile from '../tenant/profile.vue';

const { initSystemThemeConfig } = useDataThemeChange();
const { parameters, showFormCreate, formWinName, isView, dataWinName, dataWinShow, form } = toRefs(
  reactive({
    parameters: [],

    // 新增
    showFormCreate: false,
    formWinName: '配置表单定义',
    isView: true,

    dataWinName: '修改',
    dataWinShow: false,
    form: {
      id: null,
      attr_json: null,
      form_def: null
    }
  })
);
const parameterRef = ref(null);
const groupBodyRef = ref(null);

onMounted(() => {
  init();
});

const init = async () => {
  let configs = await api.project.getConfigListAll();

  configs = _.sortBy(_.filter(configs, { type: 'json' }), ['sort']);

  parameters.value = [
    {
      id: -1,
      attr_label: '系统信息',
      attr_name: '__tenant',
      type: 'custom',
      page: TenantProfile
    }
  ].concat(configs);
};

const handleParamAddShow = () => {
  // form.value = { id: null, form_def: null };
  // showFormCreate.value = true;

  handleShowEditForm({ id: null, form_def: null });
};

const handleShowEditForm = (iForm) => {
  form.value = iForm;
  // showFormCreate.value = true;

  openCompInWin(
    ParameterForm,
    {
      id: form.value.id,
      formInfo: form.value.form_def,
      useType: 'WEB',
      isShowForm: true,
      onConfirm: async () => {
        await init();
      },
      onCancel() {}
    },
    {
      title: formWinName.value,
      fullscreen: true,
      class: 'm-dialog-fullscreen'
    }
  );
};

/*
const handleCloseFormWin = () => {
  showFormCreate.value = false;
}
*/

const handleParamSelect = (param) => {
  form.value = param;
  isView.value = true;
  handleGoBox(param);
};

const handleShowUpdate = (param) => {
  form.value = _.cloneDeep(param);
  // dataWinShow.value = true;
  dataWinName.value = `修改配置【${_.get(form.value, 'attr_label') || _.get(form.value, 'form_def.form_name')}】`;

  if (param.type === 'custom') {
    openCompInWin(
      param.page,
      {
        modelValue: form.value.attr_json,
        // isSimple: true,
        isView: false,
        onConfirm: async (val) => {
          init();
        },
        onCancel() {}
      },
      {
        title: dataWinName.value,
        fullscreen: false,
        closeOnClickModal: false,
        appendToBody: true,
        confirmEventName: 'save',
        cancelEventName: 'close',
        showConfirmButton: false,
        showCancelButton: false
      }
    );
  } else {
    openCompInWin(
      $utils.getAppComp('JzlForm'),
      {
        modelValue: form.value.attr_json,
        formDef: form.value.form_def,
        isSimple: true,
        isView: false,
        onConfirm: async (val) => {
          await handleSaveData(val);
        },
        onCancel() {}
      },
      {
        width: '960px',
        title: dataWinName.value,
        fullscreen: false,
        closeOnClickModal: false,
        appendToBody: true,
        confirmEventName: 'save',
        cancelEventName: 'close',
        showConfirmButton: false,
        showCancelButton: false
      }
    );
  }
};

const handleSaveData = async (data) => {
  // console.log(data);
  // console.log(this.form.id, this.form.attr_json, this.form.form_def)

  let ret = await api.project.updateParamData(form.value.id, data);
  console.log(`-------->>>>>> `, ret, form.value.id, data);
  if (ret) {
    // this.isView = true;
    dataWinShow.value = false;
    showFormCreate.value = false;

    if (ret.attr_name === 'theme') {
      initSystemThemeConfig(ret.attr_json);
    }
    await init();
  }
};

const handleGoBox = (g) => {
  let gid = _.get(g, 'id');

  if (!gid) return;

  let targetId = `system-param-${gid}`;
  let $groupBox = parameterRef.value?.querySelector(`[id=${targetId}]`);
  let $body = groupBodyRef.value;

  // 判断是否有滚动条
  if ($body && $groupBox?.offsetTop >= 0) {
    const containerRect = $body.getBoundingClientRect();
    const elementRect = $groupBox.getBoundingClientRect();
    const scrollTop = elementRect.top - containerRect.top + $body.scrollTop;

    $body.scrollTo({
      top: scrollTop, // top - padTop,
      behavior: 'smooth'
    });
  }
};
</script>

<template>
  <div ref="parameterRef" class="param-container">
    <div class="param-menu">
      <el-scrollbar class="param-menu-scroll">
        <template v-for="param in parameters">
          <div
            class="param-head"
            :class="{ active: param.id === form.id }"
            @click="handleParamSelect(param)"
          >
            <div class="param-head-icon"></div>
            <div class="param-head-title">{{ param.attr_label || param.attr_name }}</div>
            <div class="param-head-actions">
              <JIcon
                v-if="param.type !== 'custom'"
                :icon="DFT_ICONS.layout"
                class="param-head-action-icon"
                v-tippy
                content="参数定义"
                @click.stop="handleShowEditForm(param)"
              />
              <JIcon
                :icon="DFT_ICONS.db"
                class="param-head-action-icon"
                v-tippy="{ arrow: true }"
                content="参数数据"
                @click.stop="handleShowUpdate(param)"
              />
            </div>
          </div>
        </template>
      </el-scrollbar>
      <div class="param-head" @click="handleParamAddShow">
        <JIcon :icon="DFT_ICONS.add" class="param-head-icon" />
        <div class="param-head-title">增加参数定义</div>
      </div>
    </div>

    <div class="param-body h-full overflow-y-auto" ref="groupBodyRef">
      <div>
        <template v-for="param in parameters">
          <div
            v-if="param.type === 'custom'"
            :id="`system-param-${param.id}`"
            class="data-form-container data-form-theme-simple data-form-font-sm param-body-active"
          >
            <div class="form-body">
              <div class="data-form-body h-full">
                <div class="group-box">
                  <div class="group-header">
                    <span class="title">{{ param.attr_label || param.attr_name }}</span>
                  </div>
                  <component :is="param.page" :is-view="true" />
                </div>
              </div>
            </div>
          </div>
          <JzlForm
            v-else-if="param.form_def"
            v-model="param.attr_json"
            :value="param.attr_json"
            :form-def="param.form_def"
            :is-simple="true"
            :id="`system-param-${param.id}`"
            :is-view="isView"
            @save="handleSaveData"
            @close="isView = true"
            :class="{ 'param-body-active': param.id === form.id }"
          />
        </template>
      </div>
    </div>

    <!--    <el-dialog
      v-model="showFormCreate"
      :title="formWinName"
      :fullscreen="true"
      custom-class="m-dialog-fullscreen"
      :close-on-click-modal="false"
      :append-to-body="true">
      <ParameterForm
        v-if="showFormCreate"
        @close="handleCloseFormWin"
        :id="form.id"
        :form-info.sync="form.form_def"
        :show.sync="showFormCreate"
        use-type="WEB"
        :is-show-form="true"
      />
    </el-dialog>-->

    <!--    <el-dialog
      v-model="dataWinShow"
      :title="dataWinName"
      :fullscreen="false"
      class="m-dialog-style"
      :close-on-click-modal="false"
      :append-to-body="true">
      <JzlForm
        v-if="dataWinShow && form.form_def"
        v-model="form.attr_json"
        :form-def="form.form_def"
        :is-simple="true"
        :is-view="false"
        @save="handleSaveData"
        @close="dataWinShow = false"
      />
    </el-dialog>-->
  </div>
</template>
